package com.tulele.vtool.handler;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.CombinedUserArticleInfoBySpecialSize;
import com.tulele.vtool.model.combinedEntity.CombinedUserCurImpressionInfo;
import com.tulele.vtool.model.combinedEntity.UserBrandCombinedInfo;
import com.tulele.vtool.model.reqEntity.*;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.*;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import com.tulele.vtool.utils.SysConstant;
import com.tulele.vtool.utils.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.tulele.vtool.utils.AesExpand.aesDecrypt;

@RestController
public class UserBrandInfoHandler {

    @Autowired
    private IUserBrandInfoService userBrandInfoService;

    @Autowired
    private IBrandInfoService brandInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserImpressionInfoService userImpressionInfoService;

    @Autowired
    private IArticleInfoService articleInfoService;

    @Autowired
    private IUserCommodityInfoService userCommodityInfoService;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private BPosterInfoService bPosterInfoService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private  UserGroupGzhService userGroupGzhService;

    @PostMapping(value = "/getPersonalBrand", produces = "application/json;charset=UTF-8")
    public RespData getPersonalBrand(@RequestHeader("userId") String userId) {

        Integer userIdInt = Integer.valueOf(userId);

        List<UserBrandCombinedInfo> userBrandInfo = userBrandInfoService.getUserBrandInfo(userIdInt);

        List<Map<String, Object>> brandInfo = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(userBrandInfo)) {
            userBrandInfo.forEach(info -> {
                HashMap<String, Object> infoMap = Maps.newHashMapWithExpectedSize(2);
                infoMap.put("brandId", info.getBrandId());
                infoMap.put("brandName", info.getBrandName());

                brandInfo.add(infoMap);
            });
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);
        resultMap.put("brandInfo", brandInfo);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }

    @PostMapping(value = "/storeUserBrand", produces = "application/json;charset=UTF-8")
    public RespData storeUserBrand(@RequestHeader("userId") String userId, @RequestBody StoreUserBrandReqBean storeUserBrandReqBean) {

        if (storeUserBrandReqBean == null || StringUtils.isBlank(storeUserBrandReqBean.getBrandId())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }

        userBrandInfoService.storeUserSubBrand(Integer.valueOf(userId), storeUserBrandReqBean.getBrandId());

        // 删除 redis key 看文章的次
        String verifyKey = SysConstant.LOOK_ARTICLE_TYPE + userId;
        redisCacheUtil.removeSingleCache(verifyKey);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getRecommendBrand", produces = "application/json;charset=UTF-8")
    public RespData getRecommendBrand() {

        List<BrandInfo> brandInfo = brandInfoService.getRecommendBrandInfo();

        List<Map<String, Object>> platformBrandInfo = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(brandInfo)) {
            brandInfo.forEach(info -> {
                HashMap<String, Object> infoMap = Maps.newHashMapWithExpectedSize(2);
                infoMap.put("brandId", info.getId());
                infoMap.put("brandName", info.getBrandName());

                platformBrandInfo.add(infoMap);
            });
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);
        resultMap.put("recommendBrandName", platformBrandInfo);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }

    @PostMapping(value = "/switchUserMicroStation", produces = "application/json;charset=UTF-8")
    public RespData switchUserMicroStation(@RequestHeader("userId") String userId, @RequestBody SwitchUserMicroStationReqBean switchUserMicroStationReqBean) {

        if (switchUserMicroStationReqBean == null || switchUserMicroStationReqBean.getBrandId() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        userBrandInfoService.switchUserMicroStation(Integer.valueOf(userId), switchUserMicroStationReqBean.getBrandId());

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getMicroStationHomeInfo", produces="application/json;charset=UTF-8")
    public RespData getMicroStationHomeInfo(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive, @RequestBody GetMicroStationHomeInfoReqBean getMicroStationHomeInfoReqBean) throws Exception {

        Integer userIdInt = Integer.valueOf(userId);

        if (getMicroStationHomeInfoReqBean != null && getMicroStationHomeInfoReqBean.getOtherUserId() != null) {

            userIdInt = getMicroStationHomeInfoReqBean.getOtherUserId();

        }

        //获取用户信息
        UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);
        Map<String, Object> userInfoMap = Maps.newHashMapWithExpectedSize(7);
        userInfoMap.put("userId", userInfo.getUserId());
        userInfoMap.put("nickName", userInfo.getNickName());
        userInfoMap.put("avatarUrl", userInfo.getAvatarUrl());
        userInfoMap.put("vipStatus", Optional.ofNullable(userInfo.getVipStatus()).orElse(0));
        userInfoMap.put("qrcodeUrl", userInfo.getQrcodeUrl());
        userInfoMap.put("telNum", userInfo.getTelNum());

        //获取用户印象
        List<CombinedUserCurImpressionInfo> userImpressionInfoList = userImpressionInfoService.getUserCurImpression(userIdInt);

        //获取用户品牌
        List<UserBrandCombinedInfo> userBrandCombinedInfoList = userBrandInfoService.getUserBrandInfo(userIdInt);

        //整理多微站的问题（一个用户有多个微站）
        if(userBrandCombinedInfoList!=null && userBrandCombinedInfoList.size()>0) {
            for (UserBrandCombinedInfo ubci : userBrandCombinedInfoList) {
                int falg = 0;
                if (ubci.getBrandStatus().equals(1)) {
                    falg++;
                    if (falg > 1) {
                        ubci.setBrandStatus(0);
                        UserBrandInfo ubi = new UserBrandInfo();
                        ubi.setId(ubci.getId());
                        ubi.setBrandStatus(0);
                        userBrandInfoService.updateUserBrandInfo(ubi);
                    }
                }
            }
        }

        //获取前四篇文章
        List<CombinedUserArticleInfoBySpecialSize> userArticleInfoBySpecialSizeList = articleInfoService.getUserArticleInfoBySpecialSize(userIdInt, 4);

        //获取前两个商品
        BrandInfo selectBrandInfo = userBrandInfoService.getUserSelectBrandInfo(userIdInt);
        Integer brandId = null;
        if (selectBrandInfo != null) {
            brandId = selectBrandInfo.getId();
        }
        List<UserCommodityInfo> userCommodityInfoList = userCommodityInfoService.getUserCommodityInfoBySpecialSize(userIdInt, brandId,2);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(7);
        resultMap.put("userInfo", userInfoMap);
        resultMap.put("curImpressionInfo", userImpressionInfoList);
        resultMap.put("brandInfo", userBrandCombinedInfoList);
        resultMap.put("articleInfo", userArticleInfoBySpecialSizeList);
        resultMap.put("userCommodityInfo", userCommodityInfoList);

        //先查询是否是否关注了公众号
        int userConcernStatus = Optional.ofNullable(userInfoService.getUserConcernStatus(Integer.valueOf(userId))).orElse(0);
        resultMap.put("concernStatus", userConcernStatus);

        /** 20201231 通过 推荐人 从 海报页面 到 微商页面，关联 推荐人 ljt start*/
        // 1.fromPage=1_（通过 海报页面 到 微商页面），2.推荐人 不为空，3.推荐人 不为 自己
        if (getMicroStationHomeInfoReqBean.getFromPage() != null && getMicroStationHomeInfoReqBean.getFromPage().contains("1_") && getMicroStationHomeInfoReqBean.getOtherUserId() != null && !Integer.valueOf(userId).equals(getMicroStationHomeInfoReqBean.getOtherUserId())) {
            Integer userIds = Integer.valueOf(userId);
            //判断 自己 的 推荐人 是否为空，0 - 为空。
            int refererInDB = Optional.ofNullable(userInfoService.getUserReferer(Integer.valueOf(userIds))).orElse(0);
            if (refererInDB == 0) {
                //如果没有 推荐人，则设置 邀请人 为 推荐人。
                UserInfo userInfoReferer = new UserInfo();
                userInfoReferer.setUserId(userIds);
                userInfoReferer.setReferer(getMicroStationHomeInfoReqBean.getOtherUserId());
                userInfoService.modifyWxUserInfo(userInfoReferer);

                // 判断 自己 有没有关注品牌
                List<UserBrandCombinedInfo> userBrands = userBrandInfoService.getUserBrandInfo(userIds);

                // 如果 自己 没有关注品牌，就添加 推荐人 的 品牌 给自己。
                if (userBrands == null || userBrands.size() == 0) {

                    List<UserBrandCombinedInfo> referBrands = userBrandInfoService.getUserBrandInfo2(getMicroStationHomeInfoReqBean.getOtherUserId());

                    if (referBrands != null && referBrands.size() > 0) {
                        for (UserBrandCombinedInfo ref : referBrands) {
                            userBrandInfoService.subBrandInfo(userIds, ref.getBrandId());
                        }
                    }
                }
            }

            // 海报分享人不为空 并且 海报分享人不为自己
            Integer shareUserId = getMicroStationHomeInfoReqBean.getOtherUserId();// 分享人
            // 海报id
            Integer idInt = Integer.valueOf(getMicroStationHomeInfoReqBean.getFromPage().replace("1_", ""));

            BPosterInfo posterInfo = this.bPosterInfoService.queryById(idInt);

            PlatformSysInfo platformSysInfo= sysGzhService.getPlatformSysInfo(springProfilesActive);

            String headLine = "获客海报";
            UserInfo queryUserMainInfo = userInfoService.queryUserMainInfoMine(Integer.valueOf(userId));
            String kefuMsg = String.format(SysConstant.NEW_USER_LOOK_POSTER_INFO_PUSH_A_MSG.replace(SysConstant.frontDomain,platformSysInfo.getFrontDomain()), headLine);

            int vipStatus = Optional.ofNullable(userInfoService.getUserVipStatus(shareUserId)).orElse(0);
            if (vipStatus == 1) {
                kefuMsg = String.format(SysConstant.NEW_USER_LOOK_POSTER_INFO_PUSH_B_MSG.replace(SysConstant.frontDomain,platformSysInfo.getFrontDomain()), queryUserMainInfo.getNickName(), headLine);
            }

            UserInfo userMainInfo = userInfoService.getUserMainInfo(shareUserId);

            //region （公众号做通）20210902
            if(userMainInfo!=null && !userMainInfo.getGzhCode().equals(springProfilesActive)){
                UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(springProfilesActive,shareUserId);
                if(userGroupOpenId!=null){
                    userMainInfo.setOpenId(userGroupOpenId.getOpenId());
                }
            }
            //endregion

            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
            }

            WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(userMainInfo.getOpenId()).content(kefuMsg).build();
            try {

                PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
                WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

                weixinService.getKefuService().sendKefuMessage(message);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }

            ArticleInfo articleInfo = new ArticleInfo();
            articleInfo.setId(idInt);// 海报ID
            articleInfo.setArticleTitle("获客海报");

            LookArticleInfo lookArticleInfo = new LookArticleInfo();
            lookArticleInfo.setUserId(Integer.valueOf(userId));
            lookArticleInfo.setOtherUserId(shareUserId);
            lookArticleInfo.setArticleId(idInt);

            //UserInfo lookUserInfo = userInfoService.getUserMainInfo(Integer.valueOf(userId));

            articleInfoService.lookOtherUserArticle(lookArticleInfo, articleInfo, userMainInfo.getNickName(), "5", springProfilesActive);
        }
        /** 20201231 通过 推荐人 从 海报页面 到 微商页面，关联 推荐人 ljt end*/

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/createUserBrandInfo", produces = "application/json;charset=UTF-8")
    public RespData createUserBrandInfo(@RequestHeader("userId") String userId, @RequestBody CreateUserBrandInfoReqBean createUserBrandInfoReqBean) {

        if (createUserBrandInfoReqBean == null || StringUtils.isBlank(createUserBrandInfoReqBean.getBrandName())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        BrandInfo brandInfo = new BrandInfo();
        brandInfo.setBrandName(createUserBrandInfoReqBean.getBrandName());
        brandInfo.setBrandOpenStatus(0);
        brandInfo.setBrandRecommendStatus(0);
        brandInfo.setBrandSource(2);
        brandInfo.setUserId(Integer.valueOf(userId));
        brandInfo.setCreateTime(DateUtil.getCurDate());

        int brandId = brandInfoService.recordBrandInfo(brandInfo);

        if (brandId > 0) {

            //将品牌设置为用户自己的品牌
            userBrandInfoService.storeUserSettedBrand(Integer.valueOf(userId), String.valueOf(brandId));

        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;

    }

    @PostMapping(value = "/unSubBrandInfo", produces = "application/json;charset=UTF-8")
    public RespData unSubBrandInfo(@RequestHeader("userId") String userId, @RequestBody UnSubPlatformBrandReqBean unSubPlatformBrandReqBean) {

        if (unSubPlatformBrandReqBean == null || unSubPlatformBrandReqBean.getBrandId() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }

        userBrandInfoService.unSubBrandInfo(Integer.valueOf(userId), unSubPlatformBrandReqBean.getBrandId());

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/subBrandInfo", produces = "application/json;charset=UTF-8")
    public RespData subBrandInfo(@RequestHeader("userId") String userId, @RequestBody SubPlatformBrandReqBean subPlatformBrandReqBean) {

        if (subPlatformBrandReqBean == null || subPlatformBrandReqBean.getBrandId() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }

        userBrandInfoService.subBrandInfo(Integer.valueOf(userId), subPlatformBrandReqBean.getBrandId());

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getRecommendBrandForBigCategory", produces = "application/json;charset=UTF-8")
    public RespData getRecommendBrandForBigCategory() {

        List<BrandCategory> brandCategoryInfo = brandInfoService.getAllCategory();

        List<BrandCategory> brandCategoryInfoService = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(brandCategoryInfo)) {
            brandCategoryInfo.forEach(info -> {
                BrandCategory brandCategoryVoInfo = new BrandCategory();

                List<BrandInfo> brandInfoVo = brandInfoService.getRecommendBrandForBigCategory(info.getId());

                brandCategoryVoInfo.setId(info.getId());
                brandCategoryVoInfo.setCategoryName(info.getCategoryName());
                brandCategoryVoInfo.setBrandInfoVo(brandInfoVo);

                brandCategoryInfoService.add(brandCategoryVoInfo);
            });
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(3);
        resultMap.put("brandCategoryInfoService", brandCategoryInfoService);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }
}
